<template>
	<view class="content">
		<view class="navbar">
			<view v-for="(item, index) in navList" :key="index" class="nav-item"
				:class="{current: tabCurrentIndex === index}" @click="tabCurrentIndex = index">
				{{item.text}}
			</view>
		</view>

		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem,tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadMore">
					<!-- 空白页 -->
					<empty v-if="loadingType != 'loading' && orderList.length == 0"></empty>

					<!-- 订单列表 -->
					<view v-for="(item,index) in orderList" :key="index" class="order-item">
						<view class="i-top b-b" @click="toOrderDetail(item)">
							<text class="time">{{ item.createTime }}</text>
							<text class="state" v-if="!item.afterSale"
								:style="{color:item.orderStatusColor}">{{item.orderStatusDesc}}</text>
							<text class="state" v-if="item.returnList[0].status == '3'">退款申请被拒绝</text>
							<text v-if="item.orderStatus == '4'" class="del-btn yticon icon-iconfontshanchu1"
								@click="deleteOrder(item)"></text>
						</view>

						<scroll-view v-if="item.itemList.length > 1" class="goods-box" scroll-x
							@click="toOrderDetail(item)">
							<view v-for="goods in item.itemList" :key="goods.id" class="goods-item">
								<image class="goods-img" :src="goods.skuPic" mode="aspectFill"></image>
							</view>
						</scroll-view>
						<view v-else class="goods-box-single" v-for="goods in item.itemList" :key="goods.id"
							@click="toOrderDetail(item)">
							<image class="goods-img" :src="goods.skuPic" mode="aspectFill"></image>
							<view class="right">
								<text class="title clamp">{{ goods.skuName }}</text>
								<text class="attr-box">
									<template v-for="spec in getSpce(goods.skuAttrsVals)">{{spec.key + ':' + spec.value}}</template>
								</text>
								<view class="price">{{ goods.realAmount.toFixed(2) }} <text class="num">共{{ goods.skuQuantity }}件</text></view>
							</view>
						</view>

						<!-- <view class="price-box" @click="toOrderDetail(item)">
							共
							<text class="num">{{ countSkuNum(item) }}</text>
							件商品 实付款
							<text class="price">{{ item.payAmount.toFixed(2) }}</text>
						</view> -->
						<view class="action-box b-t" v-if="!item.afterSale">
							<!-- 未付款或未发货状态可以取消订单 -->
							<button v-if="item.status == '0'" class="action-btn"
								@click="cancelOrder(item)">取消订单</button>
							<!-- 未付款状态可以发起支付 -->
							<!-- <button @click="pay(item)" class="action-btn recom" v-if="item.status=='0'">立即支付</button> -->
							<button @click="goPayPage(item)" class="action-btn recom"
								v-if="item.status=='0'">去支付</button>
							<!-- 待收货状态可以收货 -->
							<button @click="receive(item)" class="action-btn recom"
								v-if="item.status=='2'">确认收货</button>
							<!-- 已收货状态可以评价 -->
							<button @click="evaluate(item)" class="action-btn recom"
								v-if="false">去评价</button>
							<!-- 申请退款(待发货,已发货,待评价状态可以申请退款, 前提是订单未结算)，仅实物商品允许退款 -->
							<button @click="applyAfterSale(item)" class="action-btn recom"
								v-if="item.returnStatus == 0 && item.orderType != '1' && (item.status == '1' || item.status == '2' || item.status == '3') && item.returnStatus != '1' && item.returnStatus != '2'">申请退款</button>
							<button v-if="item.returnStatus == 1 || item.returnStatus == 2" disabled="disabled" @click="viewAfterSale(item)" class="action-btn" style="color:#FFFFFF !important;">{{item.returnStatus == '1'?'退款申请中':(item.returnStatus == '2' && item.orderType =='3'?'团购失败，已退款':'已退款')}}</button>
							<!-- 已支付的电子卡券商品可以查看核销码 -->
							<!-- <button @click="viewVoucher(item)" class="action-btn recom"v-if="false">查看核销码</button> -->
							<!-- <button @click="viewOrder(item)" class="action-btn">订单详情</button> -->
							<!-- 发货后的状态可以查看物流 -->
							<button @click="viewCourier(item)" class="action-btn"
								v-if="item.deliverySn != null && (item.status == '2' && item.status == '3')">查看物流</button>
						</view>
						<view class="action-box b-t" v-if="item.afterSale">
							<button @click="viewAfterSale(item)" class="action-btn">查看退款</button>
							<!-- <button @click="viewOrder(item)" class="action-btn">订单详情</button> -->
						</view>
					</view>

					<uni-load-more :status="loadingType"></uni-load-more>

				</scroll-view>
			</swiper-item>
		</swiper>
		<!-- 退款弹窗 -->
		<view class="return-masking-box">
			<view class="white-center-box">
				
			</view>
		</view>
		
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import empty from "@/components/empty";
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		components: {
			uniLoadMore,
			empty
		},
		data() {
			return {
				orderList: [],
				pageNo: 1,
				tabCurrentIndex: 0,
				loadingType: '',
				navList: [{
						state: '',
						text: '全部',
						loadingType: 'more',
						orderList: []
					},
					{
						state: '0',
						text: '待付款',
						loadingType: 'more',
						orderList: []
					},
					{
						state: '1',
						text: '待发货',
						loadingType: 'more',
						orderList: []
					},
					{
						state: '2',
						text: '待确认',
						loadingType: 'more',
						orderList: []
					},
					{
						state: '3',
						text: '已完成',
						loadingType: 'more',
						orderList: []
					},
					{
						state: '4',
						text: '已关闭',
						loadingType: 'more',
						orderList: []
					}
				],
			};
		},
		onShow(){
			this.searchOrder(this.translateTabIndex(this.tabCurrentIndex));
		},
		onLoad(options) {
			this.tabCurrentIndex = Number(options.type);
			// //查询全部订单时这里调用, 查询其他状态时因为tabCurrentIndex改变会触发changeTab方法调用查询
			// this.searchOrder(this.translateTabIndex(this.tabCurrentIndex));
		},
		//下拉刷新
		onPullDownRefresh() {
			//重新加载数据
			// this.resetPage();
			// this.searchOrder(this.translateTabIndex(this.tabCurrentIndex));
			// setTimeout(function () {
			// 	uni.stopPullDownRefresh();
			// }, 1000);
		},
		computed: {
			...mapState(['hasLogin', 'userInfo', 'footPrint']),
			getSpce(){
				return (item) => {
					if(item){
						return [JSON.parse(item)]
					}else{
						return item
					}
				}
			}
		},
		methods: {
			// 前往支付
			goPayPage(item) {
				console.log(item);
				uni.navigateTo({
					url: '../../appointment/toPayInfo/index',
					success: res => {
						res.eventChannel.emit('item', item)
					}
				})
			},
			// 支付成功或取消之后调用刷新页面
			//添加或修改成功之后回调
			refreshList() {
				this.searchOrder(this.translateTabIndex(this.tabCurrentIndex));
			},
			//加载更多
			loadMore() {
				const that = this
				if (this.loadingType === 'more') {
					this.pageNo = this.pageNo + 1;
					// this.searchOrder(this.translateTabIndex(this.tabCurrentIndex))
					let status = this.translateTabIndex(this.tabCurrentIndex)
					this.loadingType = 'loading';
					this.$api.request.getMemberOrderList({
						pageNum: this.pageNo,
						status: status
					}, res => {
						let usedList = that.orderList.slice(0)
						let newList = res.data.records
						this.orderList= [...usedList, ...newList],
						this.loadingType = res.data.current >= res.data.pages ? 'no-more' : 'more';
					});
				}
			},
			searchOrder(orderStatus) {
				let that = this;
				this.loadingType = 'loading';
				this.$api.request.getMemberOrderList({
					pageNum: this.pageNo,
					status: orderStatus
				}, res => {
					that.orderList = res.data.records;
					that.loadingType = res.data.current >= res.data.pages ? 'no-more' : 'more';
				});
			},
			countSkuNum(order) {
				let count = 0;
				order.itemList.forEach(item => count += item.skuQuantity);
				return count;
			},
			translateTabIndex(tabIndex) {
				let orderStatus = '';
				switch (tabIndex) {
					case 0:
						orderStatus = '';
						break;
					case 1:
						orderStatus = '0';
						break;
					case 2:
						orderStatus = '1';
						break;
					case 3:
						orderStatus = '2';
						break;
					case 4:
						orderStatus = '3';
						break;
					case 5:
						orderStatus = '4';
						break;
				}
				return orderStatus;
			},
			//swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				this.resetPage();
				this.searchOrder(this.translateTabIndex(this.tabCurrentIndex))
				
			},
			//删除订单
			deleteOrder(item) {
				let that = this;
				uni.showModal({
					content: '确认要删除订单吗？',
					success: (e) => {
						if (e.confirm) {
							that.$api.request.deleteMemberOrder({
								id: item.id
							}, res => {
								that.$api.msg('订单已成功删除');
								that.resetPage();
								that.searchOrder(that.translateTabIndex(that.tabCurrentIndex));
							});
						}
					}
				})
			},
			resetPage() {
				this.pageNo = 1;
				this.orderList = [];
			},
			//取消订单
			cancelOrder(item) {
				let that = this;
				uni.showModal({
					content: '确认要取消订单吗？',
					success: (e) => {
						if (e.confirm) {
							this.$api.request.memberCancelOrder({
								id: item.id
							}, res => {
								that.$api.msg('订单已成功取消');
								that.resetPage();
								that.searchOrder(that.translateTabIndex(that.tabCurrentIndex));
								// 如果使用了优惠券，则把优惠劵重置为可以使用
								if(item.couponId != null){
									that.$api.request.upCouponMode({
										ids: item.couponId,
										orderId: item.id
									}, rs => {
										if(rs.code == 200){
											console.log("优惠券修改成功");
										}
									})
								}
							});
						}
					}
				})
			},
			pay(item) {
				console.log(item);
				try {
					this.$api.request.memberSubmitOrder(item, res => {
						this.toPay(res);
					})
				} catch (e) {
					console.log(e);
				}
				// uni.navigateTo({
				//   url: '/pages/sys/shopCart/placeOrder'
				// })
			},
			toPay(data) {
				let res = JSON.parse(data.data.jsonStr)

				uni.requestPayment({
					timeStamp: res.timeStamp,
					nonceStr: res.nonceStr,
					package: res.package,
					signType: res.signType,
					paySign: res.paySign,
					success: (res) => {
						console.log("成功", res);
						this.$api.request.payNotify(data.data.user, res => {
							console.log("通知", res);
							uni.reLaunch({
								url: "/pagesA/sys/user/order"
							})
						})

					},
					fail: (err) => {
						console.log(err);
						this.$api.msg("支付失败！")
						// uni.navigateTo({
						// 	url: '/pagesA/sys/user/order?type=0'
						// });
					}
				})
			},
			receive(item) {
				let that = this;
				uni.showModal({
					content: '确认已收货吗？',
					success: (e) => {
						if (e.confirm) {
							this.$api.request.confirmReceiveOrder({
								id: item.id
							}, res => {
								that.$api.msg('确认收货成功');
								setTimeout(() => {
									that.resetPage();
									that.searchOrder(that.translateTabIndex(that
										.tabCurrentIndex));
								}, 1000)
							});
						}
					}
				})
			},
			evaluate(item) {
				uni.navigateTo({
					url: '/pages/order/evaluate?orderNo=' + item.orderNo
				})
			},
			// 跳转订单详情
			toOrderDetail(item) {
				const that = this
				this.$api.request.getOrderInfoType({
					memberId: item.memberId,
					orderId: item.id,
				}, res => {
					console.log(res);
					if (res.code == 200) {
						// 如果该订单是商品
						if (res.data == 1) {
							uni.navigateTo({
								url: '/pagesA/sys/user/orderDetail?id=' + item.id 
							});
						}
						// 如果该订单是服务
						else if (res.data == 2) {
							that.getServiceData(item)
						}
					}
				})

			},
			// 获取服务订单
			getServiceData(item) {
				uni.navigateTo({
					url: '/pagesA/appointment/service/index?orderId=' + item.id ,
				})
			},
			navProductDetail(item) {
				uni.navigateTo({
					url: '/pages/sys/home/product?id=' + item.skuId
				})
			},
			applyAfterSale(item) {
				uni.showModal({
					content: '是否申请退款？',
					success: (e) => {
						if (e.confirm) {
							// 跳转至退款申请
							uni.navigateTo({
								url: '/pagesB/order/return/applyFor',
								success: (res) => {
									res.eventChannel.emit('data', item)
								}
							})
						}
					}
				})
				
				// this.$api.request.getOrderInfoType({
				// 	memberId: '1',
				// 	orderId: item.id
				// }, res => {
				// 	if(res.code == 200){
				// 		console.log(res);
				// 		if(res.data == 2){
				// 			uni.showModal({
				// 				content: '是否申请退款？',
				// 				success: (e) => {
				// 					if (e.confirm) {
				// 						// 跳转至退款申请
				// 						uni.navigateTo({
				// 							url: '/pagesB/order/return/applyFor',
				// 							success: (res) => {
				// 								res.eventChannel.emit('data', item)
				// 							}
				// 						})
										
							
				// 					}
				// 				}
				// 			})
				// 		}else{
				// 			uni.showModal({
				// 				title: '温馨提示',
				// 				content: '发起退款前请与商城管理人员联系，\n 联系电话(13518543037), 达成一致后方可进行退款',
				// 				success: (e) => {
				// 					if (e.confirm) {
				// 						// 拨打电话
				// 						uni.makePhoneCall({
				// 							phoneNumber: "13518543037"
				// 						})
				// 					}
				// 				}
				// 			})
				// 		}
				// 	}
				// })
				
			},
			viewAfterSale(item) {
				uni.navigateTo({
					url: '/pagesA/sys/user/aftersale?id=' + item.id
				})
			},
			viewOrder(item) {
				uni.navigateTo({
					url: '/pages/order/detail?orderNo=' + item.orderNo
				})
			},
			viewCourier(item) {
				uni.navigateTo({
					url: '/pages/order/courier?courierNo=' + item.courierNo
				})
			},
			viewVoucher(item) {
				uni.navigateTo({
					url: '/pages/voucher/voucher?orderNo=' + item.orderNo
				})
			}
		},
	}
</script>

<style lang="scss">
	page,
	.content {
		background: $page-gery-light;
		height: 100%;
	}

	.swiper-box {
		height: calc(100% - 40px);
	}

	.list-scroll-content {
		height: 100%;
	}

	.navbar {
		display: flex;
		height: 40px;
		padding: 0 5px;
		background: #fff;
		box-shadow: 0 1px 5px rgba(0, 0, 0, .06);
		position: relative;
		z-index: 10;

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 15px;
			color: $font-color-dark;
			position: relative;

			&.current {
				color: #009B65;

				&:after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 44px;
					height: 0;
					border-bottom: 2px solid #009B65;
				}
			}
		}
	}

	.uni-swiper-item {
		height: auto;
	}

	.order-item {
		display: flex;
		flex-direction: column;
		background: #fff;
		margin: 24rpx 24rpx 0;
		border-radius: 16rpx;
		box-shadow: 0px 4px 20px 0px rgba(0,0,0,0.0400);
		padding: 24rpx;
		.i-top {
			display: flex;
			align-items: center;
			font-size: $font-base;
			color: $font-color-dark;
			position: relative;

			.time {
				flex: 1;
			}

			.state {
				color: $base-color;
			}

			.del-btn {
				padding: 10upx 0 10upx 36upx;
				font-size: $font-lg;
				color: $font-color-light;
				position: relative;

				&:after {
					content: '';
					width: 0;
					height: 30upx;
					border-left: 1px solid $border-color-dark;
					position: absolute;
					left: 20upx;
					top: 50%;
					transform: translateY(-50%);
				}
			}
		}

		/* 多条商品 */
		.goods-box {
			height: 160upx;
			padding: 20upx 0;
			white-space: nowrap;

			.goods-item {
				width: 120upx;
				height: 120upx;
				display: inline-block;
				margin-right: 24upx;
			}

			.goods-img {
				display: block;
				width: 100%;
				height: 100%;
			}
		}

		/* 单条商品 */
		.goods-box-single {
			display: flex;
			padding: 20upx 0;

			.goods-img {
				display: block;
				width: 140rpx;
				height: 140rpx;
				border-radius: 8rpx;
			}

			.right {
				flex: 1;
				display: flex;
				flex-direction: column;
				padding-left: 20rpx;
				overflow: hidden;
				justify-content: space-around;
				.title {
					font-size: $font-base + 2upx;
					color: $font-color-dark;
				}

				.attr-box {
					font-size: $font-sm + 2upx;
					color: $font-color-light;
					padding: 10rpx 0;
				}

				.price {
					font-size: $font-base + 2upx;
					color: #009B65;

					&:before {
						content: '￥';
						font-size: $font-sm;
					}
					.num{
						margin-left: 26rpx;
						font-size: 24rpx;
						color: #999;
					}
				}
			}
		}

		.price-box {
			display: flex;
			justify-content: flex-end;
			align-items: baseline;
			padding: 20upx 0;
			font-size: $font-sm + 2upx;
			color: $font-color-light;

			.num {
				margin: 0 8upx;
				color: $font-color-dark;
			}

			.price {
				font-size: $font-lg;
				color: $font-color-dark;

				&:before {
					content: '￥';
					font-size: $font-sm;
					margin: 0 2upx 0 8upx;
				}
			}
		}

		.action-box {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			position: relative;
		}

		.action-btn {
			width: auto;
			height: 48rpx;
			margin: 0;
			margin-left: 24rpx;
			padding: 0 15rpx;
			text-align: center;
			line-height: 48rpx;
			font-size: $font-sm;
			color: #FFFFFF;
			background: linear-gradient(328deg, #03D289 0%, #009B65 100%);
			border-radius: 30rpx;
			overflow: hidden;
			&:after {
				border-radius: 30rpx;
			}

			&.recom {
				background: #fff;
				color: #009B65;
				border-radius: 30rpx;
				border: 1rpx solid #009B65;
				&:after {
					border: none;
				}
			}
		}
	}


	/* load-more */
	.uni-load-more {
		display: flex;
		flex-direction: row;
		height: 80upx;
		align-items: center;
		justify-content: center
	}

	.uni-load-more__text {
		font-size: 28upx;
		color: #999
	}

	.uni-load-more__img {
		height: 24px;
		width: 24px;
		margin-right: 10px
	}

	.uni-load-more__img>view {
		position: absolute
	}

	.uni-load-more__img>view view {
		width: 6px;
		height: 2px;
		border-top-left-radius: 1px;
		border-bottom-left-radius: 1px;
		background: #999;
		position: absolute;
		opacity: .2;
		transform-origin: 50%;
		animation: load 1.56s ease infinite
	}

	.uni-load-more__img>view view:nth-child(1) {
		transform: rotate(90deg);
		top: 2px;
		left: 9px
	}

	.uni-load-more__img>view view:nth-child(2) {
		transform: rotate(180deg);
		top: 11px;
		right: 0
	}

	.uni-load-more__img>view view:nth-child(3) {
		transform: rotate(270deg);
		bottom: 2px;
		left: 9px
	}

	.uni-load-more__img>view view:nth-child(4) {
		top: 11px;
		left: 0
	}

	.load1,
	.load2,
	.load3 {
		height: 24px;
		width: 24px
	}

	.load2 {
		transform: rotate(30deg)
	}

	.load3 {
		transform: rotate(60deg)
	}

	.load1 view:nth-child(1) {
		animation-delay: 0s
	}

	.load2 view:nth-child(1) {
		animation-delay: .13s
	}

	.load3 view:nth-child(1) {
		animation-delay: .26s
	}

	.load1 view:nth-child(2) {
		animation-delay: .39s
	}

	.load2 view:nth-child(2) {
		animation-delay: .52s
	}

	.load3 view:nth-child(2) {
		animation-delay: .65s
	}

	.load1 view:nth-child(3) {
		animation-delay: .78s
	}

	.load2 view:nth-child(3) {
		animation-delay: .91s
	}

	.load3 view:nth-child(3) {
		animation-delay: 1.04s
	}

	.load1 view:nth-child(4) {
		animation-delay: 1.17s
	}

	.load2 view:nth-child(4) {
		animation-delay: 1.3s
	}

	.load3 view:nth-child(4) {
		animation-delay: 1.43s
	}

	@-webkit-keyframes load {
		0% {
			opacity: 1
		}

		100% {
			opacity: .2
		}
	}
	
</style>
